 /*--------------------------------------------------------
  * DOI Function for text 
  * For now just set the text with red color 
  * as the highest interest(highest number)
  * TODO: Mike would replace it with the real one here
  *-----------------------------------------------------*/
function DOIText($element){
  colorHighestDOI = "#FF0000";
  return ($element.attr('fill') == colorHighestDOI ? 1 : 0);
}
function getX($element){
  var t = $element.attr("transform");
  if(t != null){
    t = t.replace(/[a-zA-Z()]+/g,'').split(',');
    return parseFloat(t[0]); 
  }else return false;
}

function getY($element){
  var t = $element.attr("transform");
  if(t != null){
    t = t.replace(/[a-zA-Z()]+/g,'').split(',');
    return parseFloat(t[1]); 
  }else return false;
}

/*
 * Enables or disables collapsing of text. Animates between the two states.
 */
function setTextCollapse(enabled) {
  // TODO: Currently this just shows/hides all labels and icons, which is not
  // correct. Needs to actually perform and reverse text collapsing.
  if (enabled) {
    d3.select('g.text-dot-container')
      .transition()
      .style("opacity", 1.0);
    d3.selectAll('text.point_label')
      .style("opacity", 1.0)
      .transition()
      .style("opacity", 0.0)
      .transition().delay(1000)
      .style("display", "none");
  } else {
    d3.select('g.text-dot-container')
      .transition()
      .style("opacity", 0.0);
    d3.selectAll('text.point_label')
      .style("opacity", 0.0)
      .style("display", "block")
      .transition()
      .style("opacity", 1.0);
  }
}

/* ----------------------------------------------------------------
 * Function textCollapse: collapses all the collided texts into dot
 * -------------------------------------------------------------*/
function textCollapse(e){
  
  //var container = d3.select('svg')
  var $parent = $(e.tile.element);
  var container = d3.select(e.tile.element).append('g')
      .attr('class','text-dot-container');
  $parent.parent().parent().attr('class','layer layer2');
  d3.selectAll('.layer2 .point_label')
      .attr('alignment-baseline','middle')
      .attr('text-anchor','middle')
      
  //config the collaped text
  var textIcon = {
    fontSize:11,
    fontFamily:'Georgia',
    fontWeight:'bold',
    w: 11,
    h: 15,
    strokeWidth:1
  } 

  function Text($text){
    this.content = $text;
    this.x = getX($text);
    this.y = getY($text);
    this.h = $text.height();
    this.w = $text.width();
    this.doi = DOIText($text);
    this.color = $text.css('fill');
  } 

  //Select all the svg text and turn into Text object
  //Returns the array of Text object
  var textArr = function(){
    var arr = [];
    $parent.find('text.point_label').each(function(){
      arr.push(new Text($(this)));
    });
    return arr;
  } 

  function isCollided(element1, element2){
    //Assume the text is always horizontal
    var sensitivity = 0.8;
    var dhMax = (element1.h + element2.h)/2;
    var dwMax = (element1.w + element2.w)/2;
    var dx = Math.abs(element1.x - element2.x);
    var dy = Math.abs(element1.y - element2.y);
    return (dx <= sensitivity * dwMax && dy <= sensitivity * dhMax);
  }
  
  function process(){
    var collapsedTextIndex = {};
    var words = textArr();
    var group = 0;
    for(i = 0;i < words.length;i++){
      for(j = i + 1;j < words.length;j++){
        if(isCollided(words[i],words[j])){
          collapse(i,j);
        }
      }
    }

    //TODO: consider DOI
    function collapse(i,j){
      switch (collapsedTextIndex.hasOwnProperty(i)){
        case true:
          switch (collapsedTextIndex.hasOwnProperty(j)){
            case false:
              collapsedTextIndex[j] = collapsedTextIndex[i];
              createTextIcon(j);
              return;
            case true:
              return;
          }
        case false:
          switch (collapsedTextIndex.hasOwnProperty(j)){
            case true:
              collapsedTextIndex[i] = collapsedTextIndex[j];
              createTextIcon(i);
              return;
            case false:
              group += 1;
              collapsedTextIndex[i] = group;
              collapsedTextIndex[j] = group;
              createTextIcon(i);
              createTextIcon(j);
              return;
          }       
      }

      function turnIntoDot(index){
        var element = words[index];
        var group = collapsedTextIndex[index];
        var $element = element.content; 
        var text = $element.text();   
        var className = 'text-collapse-group-' + group;
        $element.css('display','none');
        container.append('circle')
          .attr('class','text-dot')
          .attr('cx',element.x)
          .attr('cy',element.y)
          .attr('r',3)
          .style('fill',element.color)
          .attr('title',text)
          .attr('class',className);
      }

      function createTextIcon(index){
        var element = words[index];
        var group = collapsedTextIndex[index];
        var $element = element.content; 
        var text = $element.text();   
        var className = 'text-collapse-group-' + group + ' text-collapse-group';
        $element.css('display','none');
        container.append('text')
          .attr('class',className)
          .text("T")
          .attr('transform',function(d){
            return 'translate(' + element.x + ',' + element.y + ')';
          })
          .attr('title',text)
          .attr('alignment-baseline','middle')
          .attr('text-anchor','middle')
          .style('fill',element.color)
          .style('font-family',textIcon.fontFamily)
          .style('font-weight',textIcon.fontWeight)
          .style('font-size',textIcon.fontSize);
        container.append('rect')
          .attr('class',className)
          .attr('width',textIcon.w)
          .attr('height',textIcon.h)
          .attr('x',element.x)
          .attr('y',element.y)
          .attr('transform',function(){
            return 'translate(-' + (textIcon.w/1.9) + ',-' + (textIcon.h/1.5) + ')'; 
          })
          .attr('rx',1)
          .attr('ry',1)
          .style('fill','none')
          .style('stroke',element.color)
          .style('stroke-width',textIcon.strokeWidth);
      }
    }
  }

  process();
  //$('circle').tooltip();

}



